#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
移除所有markdown文件中目录的脚本
支持移除多种格式的目录，包括数字编号目录和emoji目录
"""

import os
import re

def remove_toc_from_content(content):
    """从markdown内容中移除目录"""
    lines = content.split('\n')
    
    # 找到目录开始和结束的位置
    toc_start = -1
    toc_end = -1
    
    for i, line in enumerate(lines):
        # 检测目录开始 - 支持多种目录标题格式
        if (line.strip() == '## 1. 目录' or 
            line.strip() == '## 📋 目录' or 
            line.strip() == '## 目录'):
            toc_start = i
            continue
            
        # 检测目录结束的分隔符
        if toc_start >= 0 and line.strip() == '---':
            # 查找下一个非空行作为结束位置
            for j in range(i + 1, len(lines)):
                if lines[j].strip():
                    toc_end = j
                    break
            if toc_end == -1:  # 如果后面没有内容了
                toc_end = i + 1
            break
    
    if toc_start >= 0 and toc_end > toc_start:
        # 移除目录区域
        new_lines = lines[:toc_start] + lines[toc_end:]
        
        # 清理多余的空行
        cleaned_lines = []
        empty_line_count = 0
        
        for line in new_lines:
            if line.strip() == '':
                empty_line_count += 1
                if empty_line_count <= 2:  # 最多保留2个连续空行
                    cleaned_lines.append(line)
            else:
                empty_line_count = 0
                cleaned_lines.append(line)
        
        # 移除开头可能的空行
        while cleaned_lines and cleaned_lines[0].strip() == '':
            cleaned_lines.pop(0)
        
        return '\n'.join(cleaned_lines)
    
    return content

def remove_toc_from_file(file_path):
    """从单个markdown文件中移除目录"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 保存原始内容用于比较
        original_content = content
        
        # 移除目录
        new_content = remove_toc_from_content(content)
        
        # 检查是否有变化
        if new_content == original_content:
            print(f"跳过: {os.path.basename(file_path)} - 未找到目录")
            return False
        
        # 写回文件
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(new_content)
        
        print(f"成功: {os.path.basename(file_path)} - 已移除目录")
        return True
        
    except Exception as e:
        print(f"错误: {os.path.basename(file_path)} - {str(e)}")
        return False

def main():
    """主函数"""
    # 项目根目录
    root_dir = r"e:\\BaiduSyncdisk\\Android系统开发之路"
    
    # 查找所有markdown文件
    md_files = []
    for root, dirs, files in os.walk(root_dir):
        for file in files:
            if file.endswith('.md') and not file.startswith('README'):
                md_files.append(os.path.join(root, file))
    
    print(f"找到 {len(md_files)} 个markdown文件")
    print("=" * 50)
    
    # 处理每个文件
    success_count = 0
    for file_path in md_files:
        if remove_toc_from_file(file_path):
            success_count += 1
    
    print("=" * 50)
    print(f"处理完成: 成功移除 {success_count} 个文件的目录")

if __name__ == "__main__":
    main()